package edu.ccut.titan.tag.report.exporter;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.ccut.titan.tag.report.servlet.IReport;


import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;


public class HtmlReportExporter extends AbstractReportExporter {

	@Override
	protected JRAbstractExporter creatExporter() {
		return new JRHtmlExporter();
	}

	@Override
	protected void setContentType(HttpServletResponse response) {
		response.setContentType("text/html;charset=utf-8");
	}
	
	@Override
	protected OutputStream getOutputStream(HttpServletRequest request, HttpServletResponse response) throws IOException  {
		return null;
	}

	@Override
	protected void morePrint(JasperPrint print,
			HttpServletRequest request, HttpServletResponse response, OutputStream outputStream) throws IOException {

		super.morePrint(print, request, response, outputStream);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("/report/printView.jsp");
		
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void setParameters(JRAbstractExporter exporter,
			HttpServletRequest request, HttpServletResponse response) {
		
		super.setParameters(exporter, request, response);
		
		exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request
				.getContextPath() + "/servlets/image?image=");
		StringBuffer buffer = new StringBuffer();
		exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, buffer);

		String pageIndex = request.getParameter(IReport.HTML_PAGE_INDEX);
		if (pageIndex == null) {
			pageIndex = "0";
		}
		exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.parseInt(pageIndex));
		exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
		exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
		exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
		exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");
		exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
				Boolean.FALSE);

		request.setAttribute(IReport.HTML_OUT_BUFFER, buffer);
	}
}
